package model

import (
	"errors"
	"gorm.io/gorm"
	"tapay-ws/global"
	"time"
)

type UserOnline struct {
	ID        uint32              `json:"id"`
	Uid       uint32              `json:"uid"`        //用户id
	UserType  uint8               `json:"user_type"`  //用户类型
	Status    global.OnlineStatus `json:"status"`     //在线状态
	StartTime uint32              `json:"start_time"` //开始时间
	EndTime   uint32              `json:"end_time"`   //结束时间
}

func (o *UserOnline) TableName() string {
	return "tata.base_user_online"
}

func (o *UserOnline) Create(db *gorm.DB) error {
	return db.Omit("id").Create(o).Error
}

func (o *UserOnline) BeforeCreate(*gorm.DB) error {
	o.StartTime = uint32(time.Now().Unix())
	o.Status = global.StatusOnline
	return nil
}

func (o *UserOnline) UpdateOffline(db *gorm.DB) error {
	data := map[string]interface{}{
		"status":   global.StatusOffline,
		"end_time": time.Now().Unix(),
	}
	result := db.Table(o.TableName()).Where("uid = ? and status = ? and user_type = ? ", o.Uid, global.StatusOnline, o.UserType).Updates(data)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

func (o *UserOnline) BuildWhere(db *gorm.DB) *gorm.DB {
	if o.Uid > 0 {
		db = db.Where("uid = ?", o.Uid)
	}
	if o.UserType > 0 {
		db = db.Where("user_type = ?", o.UserType)
	}
	if o.Status > 0 {
		db = db.Where("status = ?", o.Status)
	}
	return db
}

func (o *UserOnline) Count(db *gorm.DB) (int, error) {
	var cnt int64
	db = o.BuildWhere(db)
	err := db.Table(o.TableName()).Count(&cnt).Error
	if err != nil {
		return 0, err
	}
	return int(cnt), nil
}

func (o *UserOnline) LastOne(db *gorm.DB) (*UserOnline, error) {
	var obj UserOnline
	db = o.BuildWhere(db)
	err := db.Table(o.TableName()).Last(&obj).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &obj, nil
}

func (o *UserOnline) RefreshOnline(db *gorm.DB) error {
	data := map[string]interface{}{
		"status":   global.StatusOnline,
		"end_time": 0,
	}
	return db.Table(o.TableName()).Where("id = ?", o.ID).Updates(data).Error
}
